<?php
/*
 * ebiz front
 *
 * UtilityController
 *
 * @author allen
 *
 */
require_once '../app/core/controllers/BaseController.php';
require_once '../app/views/UtilityView.php';
require_once '../app/services/CustomerService.php';
require_once '../app/services/AAService.php';
require_once '../app/core/utils/HttpUtil.class.php';
require_once '../app/services/ShoppingCartService.php';
require_once '../app/views/HeaderView.php';
require_once '../app/services/AreaService.php';
require_once '../app/services/OrderService.php';
require_once '../app/services/ProductService.php';
require_once '../app/constants/Order.php';
require_once '../app/util/Pager.php';
require_once '../app/util/CommonUtil.php';
require_once '../app/constants/ConfigConstants.php';

require_once '../app/services/UserPointService.php';
require_once '../app/util/ChequeRuleUtil.php';
///////////////////////////////////
require_once '../app/views/HeaderView.php';
////////////////////////////

require_once '../app/services/VoteService.php';
require_once '../app/services/EmailService.php';
require_once '../app/services/PromotionImplService.php';
require_once '../app/component/MailUtil.php';

class UtilityController extends BaseController {

    public function select(){
    	CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/controllers/ImageController.php';
        $imageController = new ImageController();
        $captchaImg = $imageController->indexAction();
        $imageController1 = new ImageController();
        $captchaImg1 = $imageController1->indexAction(1);
        $areaService = new AreaService();
        $province = $areaService->getAllProvince();
        $campuses = $areaService->getCampusByDictId(1,0);
        require_once '../app/views/QuickRegisterView.php';
        exit();
    }

    public function login(){
        CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/controllers/ImageController.php';
        $imageController = new ImageController();
        $captchaImg = $imageController->indexAction(1);
        require_once '../app/views/LoginView.php';
        exit();
    }

	public function register(){
        CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];

 //show the allSchool info
        $areaService = new AreaService();
        $province = $areaService->getAllProvince();
        $campuses = $areaService->getCampusByDictId(1,0);
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/controllers/ImageController.php';
        $imageController = new ImageController();
        $captchaImg = $imageController->indexAction();
        require_once '../app/views/RegisterView.php';
//        $view = new UtilityView();
//        echo $view->render("getRegisterView");
        exit();
    }

    public function registersuccess(){
    	CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/views/RegisterSuccessView.php';
    }

    public function activesuccess(){
    	CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/views/ActiveSuccessView.php';
    }

    public function activefailure(){
    	CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/views/ActiveFailureView.php';
    }
    
    public function resendactiveemail(){
    	if(AAService::isLogin() && !AAService::isActive()){
    		$config = $GLOBALS["config"];
            require_once "../". $GLOBALS["local"] ."/"."utility.php";
    	    $userId = AAService::getCustomer();
	        $customerService = new CustomerService();
	        //发邮件让用户激活
	        $customerService->activeUser($userId);
	        return true;
    	}else{
            return false;
    	}
    }

	public function activation(){     //activation user function
        CommonUtil::startTimeFunction();
        $activate_key = HttpUtil::getGetString('uid');
        $activation = base64_decode($activate_key);
        $param = explode('-', $activation);
        $path = "";    //not used , used in select
        $id = $param[0];
        $customerService = new CustomerService();
        $result = $customerService->activation($id, $activate_key);
        switch ($result){
            case 1:
//                $show = "Your status are activation! Welcome!";
                //更新用户状态
            	AAService::setStatus(1);
                $userPointService = new UserPointService();
                $userPointService->updatePoint($id, 0, 1);
                header("Location: http://".ConfigConstants::$domainPath."/u/activesuccess");
                break;
            case 0:
//                $show = "Yours activate_key are error or time is overtime!";
//                break;
            case -1:
//                $show = "You are invalidation user!";
                //$show = "Your account already activation or the active time is overtime.";
                header("Location: http://".ConfigConstants::$domainPath."/u/activefailure");
                break;
        }
        exit();
    }

    public function findpassword(){
        CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/views/FindPasswordView.php';
        exit();
    }

    public function findpasswordsuccess(){
    	CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once '../app/views/FindPasswordSuccessView.php';
    }

    public function updatepasswordsuccess(){
    	CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        $title = "重置密码完成  - 阿基米米网上商城";
        $loginAction = "UtilFunction.gotoUrl('/u/login')";
        $message = '<h3>'.UPDATEPASSWORSUCCESSINFO.'</h3>';
        $message .= '<span style="color:#0000ff;cursor:pointer;" onclick="'.$loginAction.'">'.ENTERLOGINPAGE.'</span>';
        $message .= '<br/><br/><br/><br/>' ;
        require_once '../app/views/MessageView.php';
        exit();
    }

    public function updatepassword(){
        CommonUtil::startTimeFunction();
        $config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        $getPasswordKey = HttpUtil::getGetString('getPasswordKey');
        require_once '../app/views/UpdatePasswordView.php';
        exit();
    }

    public function sendemail(){    //prompt user the email already send
        CommonUtil::startTimeFunction();
    	$view = new UtilityView();
    	echo $view->render("sendEmail");
        exit();
    }

    public function cart(){ //show the shopping cart view
        CommonUtil::startTimeFunction();
    	$path = "../". $GLOBALS["local"] ."/"."shoppingCart.php";
        require_once $path;
        $config = $GLOBALS["config"];
        $headerView = HeaderView::getCommonHeaderView();
        $footerView = FooterView::getCommonFooterView();
        $shoppingCartInfo = array();
        $shoppingcartService = new ShoppingCartService();
        if(AAService::isLogin()){  //query from DB
            $customerId = AAService::getCustomer();
	        $shoppingCartInfo = $shoppingcartService->getShoppingcartInfoByCustomerId($customerId);   //used item id to get the shoppingcart info
        }else{  //query from cookie
        	$shoppingCartInfo = $shoppingcartService->getShoppingCartInfoFromCookie();
        }

        require_once '../app/views/ShoppingCartView.php';
        exit();
    }

//    public function flashCount(){   //use in ajax flash count in header view//do not to used
//        $items = 0;
//        $total = 0;
//        $result = array();
//        $shoppingcartService = new ShoppingcartService();
////        if(isset($_SESSION['customerId']) && $_SESSION['customerId'] > 0){  //user already login
//        if(AAService::isLogin()){  //user already login
////          $customerId = $_SESSION['customerId'];
//            $customerId = AAService::getCustomer();
//            $result = $shoppingcartService->showItemAndTotalByCustomerId($customerId);    //set default customer id is '1'
//        }else{
//            $result = $shoppingcartService->showItemAndTotalFromCookie();
//        }
//        if(!empty($result[0])){
//            $items = $result[0];
//        }
//        if(!empty($result[1])){
//            $total = $result[1];
//        }
//    	$result = array("item"=>$items, "total"=>$total);
//    	echo json_encode($result);
//    }

    /**
     * this is show the check out view
     */
    public function checkout(){
        CommonUtil::startTimeFunction();
        $path1 = "../". $GLOBALS["local"] ."/"."checkOut.php";   //get the internationalization file
        $path2 = "../". $GLOBALS["local"] ."/"."shoppingCart.php";   //get the internationalization file
        require_once $path1;
        require_once $path2;
        $config = $GLOBALS["config"];
        //set the value of the view will showed
        $getShippingExpectList = array();
//        $getStateNameList = Order::getStateNameList();
//        asort($getStateNameList);
//        $getShippingExpectList = Order::getShippingExpectListFromDB();
//        $getPaymentMethodFromDB = Order::getPaymentMethodFromDB();
        $orderService = new OrderService();
        $getShippingExpectList = $orderService->getShippingExpectListFromDB();
        $getPaymentMethodFromDB = $orderService->getPaymentMethodFromDB();
        $getCardTypeList = Order::getCardTypeList();
        $getMonthList = Order::getMonthList();
        $getCountryList =  Order::getCountryNameList();
//      echo AAService::isLogin()."========".AAService::isValidateForHttps()."-------";die;
        if(AAService::isLogin() && AAService::isValidateForHttps()){
        	//获得自动打折信息
        	$promotionImplService = new PromotionImplService();
        	$strCodes = $promotionImplService->getAutoPromotion();
        	
            $customerId = AAService::getCustomer();
            $shoppingcartService = new ShoppingCartService();
            $areaService = new AreaService();
            //show the top 5 address to select for user
            $selectAddress = array();
            $topAddress = $shoppingcartService->getAddressByCustomerId($customerId);
            $selectAddress = $orderService->getAddressTitle($topAddress);
            //show the goods will to show in checkout page
            $shoppingCartInfoToCheckout = $shoppingcartService->getShoppingcartInfoToCheckoutByCustomerId($customerId);

            $shipRule = $orderService->getShipRule($shoppingCartInfoToCheckout);//set the type in hidden textbox
            //show the allSchool info
            $province = $areaService->getAllProvince();
            $campuses = $areaService->getCampusByDictId(1);
            if(empty($shoppingCartInfoToCheckout)){
                header("Location: http://".ConfigConstants::$domainPath."/u/cart");
                exit();
            }
            require_once '../app/views/CheckoutView.php';
            CommonUtil::endTimeFunction();
            CommonUtil::getDBConnectionNumber();
            exit();
        }else{
            $url = $GLOBALS["SSLProtocol"] . "://".ConfigConstants::$domainPath . "/u/checkout";
            setcookie("url", $url, time() + 3600*24, '/');
            header("Location: ".$GLOBALS["SSLProtocol"]."://".ConfigConstants::$domainPath."/u/select");
            exit();
        }
    }

    /**
     * success order view
     */
    public function successorder(){
    	$config = $GLOBALS["config"];
        require_once "../". $GLOBALS["local"] ."/"."utility.php";
        require_once "../". $GLOBALS["local"] ."/"."common.php";
    	$orderService = new OrderService();
    	$orderIdBase64 = HttpUtil::getGetString("orderId");
        $orderId = base64_decode(HttpUtil::getGetString("orderId"));
        //$orderId = "2";
        //get the order info
        $orderInfo = $orderService->getOrderInfoById($orderId);
        //get the status to judje the order status ( campuses = 11 or online payment = 1)
        $orderStatus = $orderInfo[0]["status"];
        //get the order item info
        $orderItemInfo = $orderService->getOrderItemInfoByOrderId($orderId);
        $isInvoice = $orderInfo[0]["invoice"] == "不需要发票" ? false : true;
        if(AAService::isLogin()){
	        //提交订单发送邮件
	        $userId =  $orderInfo[0]["user_id"];//得到用户id
	        $customerService = new CustomerService();
	        $userInfo = $customerService->getUserCertfByUserId($userId);
	        $username = $userInfo[0]["name"];//得到用户name
	        $userEmail = $userInfo[0]["email"];//得到用户email
	        $userCertf = $userInfo[0]["certf"];//得到用户类型
	        $status = $userInfo[0]["status"];//得到用户状态是否激活
	        if(!empty($status)){
		        $result = array( "orderInfo" => $orderInfo, "orderItemInfo" => $orderItemInfo, "username" => $username, "email" => $userEmail );
		        $emailService = new EmailService();
		        $emailTitle = ORDERSUBMIT;//邮件title
		        $emailBody = $emailService->orderSubmitEmail($result);//获得邮件主体内容
		        if($userCertf == 1){//普通用户发邮件
		            MailUtil::sendMail($userEmail, $emailTitle, $emailBody);
		        }
	        }
        }
    	require_once '../app/views/SuccessOrderView.php';
    }

    /**
     * show the payment success info
     */
    public function paymentinfo(){
    	$config = $GLOBALS["config"];
        require_once '../app/views/PaymentInfoView.php';
        exit;
    }


    /**
     * this is a testing function
     */
    public function test(){
    	$a = 1;
    	if(empty($a)){
    	   echo "==========";
    	}else{
    	   echo "-------";
    	}
    	exit;
    	
    	require_once '../app/services/UserInfoService.php';
    	$e = new UserInfoService();
    	$p = array(
            'customer_id' => 1,
            'product_item_id' => 2,
            'comment' => "aaa",
            'created' => date('Y-m-d H:i:s'),
            'modified' => date('Y-m-d H:i:s')
        );
    	$e->saveUserWishlistInfo($p);
//    	var_dump($a);
//    	require_once '../app/services/UserPointService.php';
//    	$UserPointService = new UserPointService();
//    	echo $UserPointService->convertMoney(1, 500);
    	
    	
    	exit;
    	
    	
    }

    public function getareadict(){
    	$level = HttpUtil::getPostString('level');
    	$parentId = HttpUtil::getPostString('parentId');
    	$areaService = new AreaService();
    	$params = array($parentId,$level);
    	$dicts = $areaService->getAreaDicts($params);

    	echo json_encode($dicts);
    	exit;
    }

    /**
     * Display apply page
     * @author M.Wang
     */
    public function campusapply(){
        AAService::isLogin(true);
        if(!AAService::isActive()){
    		header("Location: /userinfo/index");
    	    exit();
    	}
        $config = $GLOBALS["config"];
    	require_once "../". $GLOBALS["local"] ."/"."utility.php";
    	require_once '../app/views/CampusApplyView.php';
    	$campusApplyView = new CampusApplyView();
    	echo $campusApplyView->getPage();
        exit();

    }


    public function randomp(){
        $productService = new ProductService();
        $arr_product = $productService->getRandomProduct();
        header('Location:/p/' . urlencode($arr_product['url_title']) );
        exit;
    }

    public function flash(){
        require_once '../app/views/flash.php';
    }

/*
 * Steve
 */
    public function mencostume(){
    	$config = $GLOBALS["config"];
    	require_once "../". $GLOBALS["local"] ."/"."utility.php";
    	require_once '../app/views/static/MenCostumeView.php';
    }

    public function announcement(){
        require_once '../app/views/static/Web_Announcement.php';
    }
    
    public function help(){
    	$type = HttpUtil::getGetString('type');
    	switch($type){
    		case 'buyprocess':
    		    require_once '../app/views/help/BuyProcessView.php';
    		    break;
    		case 'order' :
    			require_once '../app/views/help/OrderView.php';
    		    break;
    		case 'deliver' :
    			require_once '../app/views/help/DeliveryHelpView.php';
    		    break;
    		case 'invoice' :
    			require_once '../app/views/help/InvoiceView.php';
    		    break;
    		case 'faq' :
    			require_once '../app/views/help/FaqView.php';
    		    break;
    		case 'rank' :
    			require_once '../app/views/help/RankView.php';
    		    break;
    		case 'mark' :
    			require_once '../app/views/help/MarkView.php';
    		    break;
    	    case 'service' :
    	    	$link = HttpUtil::getGetString('link');
    	    	switch($link){
    	    		case 'mobile':
    	    			$subject = '手机及手机配件';
    	    			break;
    	    	    case 'notebook':
    	    			$subject = '笔记本电脑及配件';
    	    			break;
    	    	    case 'pc':
    	    			$subject = '电脑外设产品';
    	    			break;
    	    		case 'mp3':
    	    			$subject = '数码影音';
    	    			break;
    	    		case 'cos':
    	    			$subject = '服装、包、鞋类商品';
    	    			break;
    	    		case 'mak':
    	    			$subject = '化妆品';
    	    			break;
    	    		case 'tri':
    	    			$subject = '饰品';
    	    			break;
    	    		case 'jiadian':
    	    			$subject = '小家电';
    	    			break;
    	    		case 'sport':
    	    			$subject = '体育用品';
    	    			break;	
    	    	}
    	    	$title = $subject.' - 售后服务规则  - 阿基米米网上商城';
    			require_once '../app/views/help/ServiceView.php';
    		    break;
    		case 'common' :
    	    	$link = HttpUtil::getGetString('link');
    	        switch($link){
    	    		case 'mobile':
    	    			$subject = '手机及手机配件';
    	    			break;
    	    		case 'dic':
    	    			$subject = '数码相机及配件';
    	    			break;
    	    	    case 'notebook':
    	    			$subject = '笔记本电脑及配件';
    	    			break;
    	    	    case 'pj':
    	    			$subject = '电脑外设产品';
    	    			break;
    	    		case 'mp3':
    	    			$subject = '数码影音';
    	    			break;
    	    		case 'cos':
    	    			$subject = '服饰';
    	    			break;
    	    		case 'mak':
    	    			$subject = '化妆品';
    	    			break;
    	    		case 'tri':
    	    			$subject = '礼品饰品';
    	    			break;
    	    		case 'jiadian':
    	    			$subject = '百货家电';
    	    			break;
    	    		case 'sport':
    	    			$subject = '体育用品';
    	    			break;	
    	    	}
    	    	$title = $subject.' - 购物常识介绍  - 阿基米米网上商城';
    			require_once '../app/views/help/CommonView.php';
    		    break;
    	    case 'aboutakimimi' :
    			require_once '../app/views/help/akimimi/AboutAkimimiView.php';
    		    break;
    		case 'mimiboy' :
    			require_once '../app/views/help/akimimi/MimiBoyView.php';
    		    break;
    		case 'partner' :
    			require_once '../app/views/help/akimimi/PartnerView.php';
    		    break;
    		case 'campus' :
    			require_once '../app/views/help/akimimi/CampusView.php';
    		    break;
    		case 'growth' :
    			require_once '../app/views/help/akimimi/GrowthView.php';
    		    break;
    	    case 'event' :
    	    	$ac = HttpUtil::getGetString('ac');
    	    	$fileName = 'AC'.$ac.'View.php';
    	    	require_once '../app/views/help/akimimi/'.$fileName;
    	    	 break;
    	    case 'link' :
    			require_once '../app/views/help/akimimi/LinkView.php';
    		    break;
    		case 'contact' :
    			require_once '../app/views/help/akimimi/ContactView.php';
    		    break;
    		case 'join' :
    			require_once '../app/views/help/akimimi/JoinView.php';
    		    break;
    		
    	} 
    	
    }
    
    public function agreement(){
        require_once '../app/views/static/user_agreement.php';    	
    }
    
    /**
     * 显示商品所有评价信息
     */
    public function showallopinion(){     	
        $itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $headerView = HeaderView::getCommonHeaderView();
        $footerView = FooterView::getCommonFooterView();
        $pid = HttpUtil::getGetString("pid");
        $pid = empty($pid) ? 0 : $pid;
        $voteService = new VoteService();
        //得到该商品评价的用户人数
        $opinionUserNumber = $voteService->getCommentsUserNumberByProductId($pid);
        //得到该商品评价的数目
        $opinionItemNumber = $voteService->getOpinionNumber($pid);
        //得到所有产品的所有评论信息或指定产品的所有评论信息
        $opinionInfo = $voteService->getAllCommentsByProductId($pid, 0, $itemsPerPage);
        //生成分页html
        $pager = new Pager();
        $pager->setJavascriptFunction("javascript:ProductAllOpinion.ajaxPaginate");
        $headerPaginate = $pager->paginate(1, $opinionItemNumber, "", $itemsPerPage);
        
        require_once '../app/views/ProductAllOpinionView.php';
        exit();
        
    }
    
}